﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

namespace ScriptBox
{
    public class TalonsUpdate
    {
        private string CurrentVersion { get; set; }
        public string NewVersion { get; set; }
        private string Owner { get; set; }
        private string Repo { get; set; }
        private string UpdateUrl { get; set; }
        private string UpdateFilePath { get; set; }

        public event EventHandler<string> UpdateChecked;

        WindowUpdate updateWin;


        public TalonsUpdate(string owner, string repo)
        {
            Owner = owner;
            Repo = repo;
        }

        /// <summary>
        /// 检查更新，如果获取到版本号则触发事件
        /// </summary>
        public void CheckUpdate()
        {
            new Thread(() =>
            {
                string newVersion = GetLatestVersion_Gitee(Owner, Repo);
                if (newVersion != null)
                {
                    UpdateChecked?.Invoke(this, newVersion);
                }
            }).Start();
        }
        /// <summary>
        /// 检查更新，如果获取到版本号且与当前版本不同则触发事件
        /// </summary>
        public void CheckUpdate(string currentVersion)
        {
            CurrentVersion = currentVersion;
            new Thread(() =>
            {
                NewVersion = GetLatestVersion_Gitee(Owner, Repo);
                if (NewVersion != null && !currentVersion.Equals(NewVersion))
                {
                    UpdateChecked?.Invoke(this, NewVersion);
                }
            }).Start();
        }

        /// <summary>
        /// 获取gitee仓库最新版本号
        /// </summary>
        /// <param name="owner"></param>
        /// <param name="repo"></param>
        /// <returns></returns>
        private string GetLatestVersion_Gitee(string owner, string repo)
        {
            string apiUrl = $"https://gitee.com/api/v5/repos/{owner}/{repo}/releases/latest";
            string token = ""; // 请替换为你自己的Gitee Access Token

            // 1. 创建请求对象
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiUrl);
            request.Method = "GET";
            request.UserAgent = "Mozilla/5.0";
            request.Headers.Add("Authorization", "Bearer " + token);

            try
            {
                // 2. 发送请求并获取响应
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                Stream stream = response.GetResponseStream();
                StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
                string content = reader.ReadToEnd();
                reader.Close();
                stream.Close();
                response.Close();

                // 3. 解析API返回的JSON数据，获取最新版本号
                JObject obj = JObject.Parse(content);
                if (obj.TryGetValue("tag_name", out JToken jToken))
                {
                    string latestVersion = jToken.Value<string>().Substring(1); // 去掉版本号前的字符"v"

                    //解析下载链接
                    foreach (JObject asset in obj["assets"])
                    {
                        string downloadUrl = (string)asset["browser_download_url"];
                        if(downloadUrl.Contains("exe"))
                        {
                            UpdateUrl = downloadUrl;
                        }
                    }
                    return latestVersion;
                }
                else
                {
                    //Console.WriteLine("Failed to fetch latest version.");
                    return null;
                }
            }
            catch (Exception )
            {
                //Console.WriteLine("Exception: " + ex.Message);
                return null;
            }
        }
        /// <summary>
        /// 用默认浏览器访问仓库release页面
        /// </summary>
        /// <param name="owner"></param>
        /// <param name="repo"></param>
        public void OpenRepoRelease_Gitee()
        {
            OpenRepoRelease_Gitee(Owner, Repo);
        }
        /// <summary>
        /// 用默认浏览器访问仓库release页面
        /// </summary>
        /// <param name="owner"></param>
        /// <param name="repo"></param>
        public void OpenRepoRelease_Gitee(string owner, string repo)
        {
            string url = string.Format("https://gitee.com/{0}/{1}/releases", owner, repo);
            System.Diagnostics.Process.Start(url);
        }

        /// <summary>
        /// 开始更新
        /// </summary>
        public void StartUpdate()
        {
            // 修改下载路径为临时文件夹
            string tempPath = Path.GetTempPath();
            
            updateWin = new WindowUpdate(NewVersion);
            updateWin.Show();
            DownloadFile(UpdateUrl, tempPath);
        }
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="savePath"></param>
        public void DownloadFile(string url, string savePath)
        {
            try
            {
                var fileName = Path.GetFileName(new Uri(url).AbsolutePath);
                UpdateFilePath = Path.Combine(savePath, fileName);
                WebClient client = new WebClient();
                
                // 添加证书验证忽略（针对HTTPS证书错误）
                ServicePointManager.ServerCertificateValidationCallback = (s, cert, chain, ssl) => true;
                
                // 订阅事件
                client.DownloadProgressChanged += OnDownloadProgressChanged;
                client.DownloadFileCompleted += OnDownloadFileCompleted;
            
                // 添加超时设置
                client.DownloadFileAsync(new Uri(url), UpdateFilePath);
            }
            catch (WebException ex)
            {
                Application.Current.Dispatcher.Invoke(() => 
                {
                    MessageBox.Show($"网络错误：{GetWebExceptionMessage(ex)}", "下载失败");
                    updateWin?.Close();
                });
            }
            catch (UriFormatException)
            {
                Application.Current.Dispatcher.Invoke(() => 
                {
                    MessageBox.Show("无效的下载地址格式", "配置错误");
                    updateWin?.Close();
                });
            }
        }

        // 添加WebException解析方法
        private string GetWebExceptionMessage(WebException ex)
        {
            if (ex.Status == WebExceptionStatus.ConnectFailure)
                return "无法连接服务器";
            if (ex.Response is HttpWebResponse response)
                return $"HTTP错误 {(int)response.StatusCode} - {response.StatusDescription}";
            return ex.Message;
        }

        private void OnDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            Application.Current.Dispatcher.Invoke(() => {
                updateWin.ProgressBar_Update.Value = e.ProgressPercentage;
            });
        }

        private void OnDownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                if (e.Error != null)
                {
                    updateWin.Close();
                    MessageBox.Show($"更新下载失败：{e.Error.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    if (File.Exists(UpdateFilePath))
                    {
                        Process.Start(UpdateFilePath);
                    }
                    updateWin.Close();
                }
                System.Environment.Exit(System.Environment.ExitCode);
            });
        }
    }
}
